<template>
    <view class="container">
        <tui-tabs :tabs="tabs" :isFixed="scrollTop>=0" :currentTab="currentTab" selectedColor="#E41F19"
            sliderBgColor="#E41F19" @change="change" itemWidth="20%"></tui-tabs>
        <view :class="{'tui-order-list':scrollTop>=0}">
            <scroll-view scroll-y="true" class="order-scroll" :refresher-enabled="true" :refresher-triggered="refresherTriggered" @refresherrefresh="onRefresh" @scrolltolower="onLoadMore" lower-threshold="120">
            <!-- 动态渲染订单 -->
            <view class="tui-order-item" v-for="(order, orderIndex) in orders" :key="orderIndex">
                <tui-list-cell :hover="false" lineLeft="0">
                    <view class="tui-goods-title">
                        <view class="tui-order-info">
                            <view class="tui-order-number">
                                订单号：{{ order.no }}
                                <view class="tui-copy-btn" @click.stop="copyOrderNo(order.no)">
                                    复制
                                </view>
                            </view>
                            <view class="tui-order-time">下单时间：{{ formatOrderCreateTime(order.createTime) }}</view>
                        </view>
                        <view class="tui-order-status">
                            <view v-if="order.status === 0 && isOrderExpired(order)" class="tui-order-expired">
                                订单已过期
                            </view>
                            <view v-else-if="order.status === 0" class="tui-order-status-content">
                                <text>{{ getStatusText(order.status) }}</text>
                                <text v-if="getOrderRemainingTime(order) > 0" class="tui-order-countdown">
                                    剩余：{{ formatOrderTime(getOrderRemainingTime(order)) }}
                                </text>
                            </view>
                            <view v-else>
                                {{ getStatusText(order.status) }}
                                <!-- 显示售后状态 -->
                                <view v-if="hasAfterSaleInProgress(order)" class="tui-refund-status">
                                    {{ getRefundStatusText(order) }}
                                </view>
                            </view>
                        </view>
                    </view>
                </tui-list-cell>
                <!-- 动态渲染订单中的商品 -->
                <block v-for="(item, index) in order.items" :key="index">
                    <tui-list-cell padding="0" @click="viewOrder(order.id)">
                        <view class="tui-goods-item">
                            <image :src="item.picUrl" class="tui-goods-img"></image>
                            <view class="tui-goods-center">
                                <view class="tui-goods-name">{{ item.spuName }}</view>
                                <view class="tui-goods-attr">
                                    <span v-for="property in item.properties" :key="property.propertyId">
                                        {{ property.propertyName }}: {{ property.valueName }}
                                    </span>
                                </view>
                            </view>
                            <view class="tui-price-right">
                                <view>￥{{ (item.payPrice / 100).toFixed(2) }}</view>
                                <view>x{{ item.count }}</view>
                            </view>
                        </view>
                    </tui-list-cell>
                </block>
                <tui-list-cell :hover="false" unlined>
                    <view class="tui-goods-price">
                        <view>共{{ order.productCount }}件商品 合计：</view>
                        <view class="tui-size-24">￥</view>
                        <view class="tui-price-large">{{ (order.payPrice / 100).toFixed(2) }}</view>
                    </view>
                </tui-list-cell>
                 <!-- 动态显示按钮 -->
                 <view class="tui-order-btn">
                     <template v-if="order.status === 0">
                         <!-- 待支付操作 -->
                         <view class="tui-btn-ml">
                             <tui-button type="black" plain width="152rpx" height="56rpx" :size="26" shape="circle"
                                 @click.stop="cancelOrder(order.id)">取消订单</tui-button>
                         </view>
                         <view class="tui-btn-ml" v-if="!isOrderExpired(order)">
                             <tui-button type="danger" plain width="152rpx" height="56rpx" :size="26" shape="circle"
                                 @click.stop="continuePayment(order)">继续支付</tui-button>
                         </view>
                     </template>
                     <template v-else-if="order.status === 10">
                         <!-- 待发货操作：支持申请售后/退货 -->
                         <view class="tui-btn-ml" v-if="canApplyAfterSale(order)">
                             <tui-button type="warning" plain width="152rpx" height="56rpx" :size="26" shape="circle"
                                 @click.stop="applyAfterSale(order)">申请售后</tui-button>
                         </view>
                         <view class="tui-btn-ml" v-else-if="hasAfterSaleInProgress(order)">
                             <tui-button type="info" plain width="152rpx" height="56rpx" :size="26" shape="circle"
                                 @click.stop="viewAfterSaleStatus(order)">售后进度</tui-button>
                         </view>
                     </template>
                     <template v-else-if="order.status === 20">
                         <!-- 已发货操作 -->
                         <view class="tui-btn-ml">
                             <tui-button type="danger" plain width="152rpx" height="56rpx" :size="26" shape="circle"
                                 @click.stop="confirmOrder(order.id)">确认收货</tui-button>
                         </view>
                         <!-- 申请售后/退货按钮 -->
                         <view class="tui-btn-ml" v-if="canApplyAfterSale(order)">
                             <tui-button type="warning" plain width="152rpx" height="56rpx" :size="26" shape="circle"
                                 @click.stop="applyAfterSale(order)">申请售后</tui-button>
                         </view>
                         <view class="tui-btn-ml" v-else-if="hasAfterSaleInProgress(order)">
                             <tui-button type="info" plain width="152rpx" height="56rpx" :size="26" shape="circle"
                                 @click.stop="viewAfterSaleStatus(order)">售后进度</tui-button>
                         </view>
                     </template>
                     <template v-else-if="order.status === 30">
                         <!-- 已完成操作 -->
                         <view class="tui-btn-ml" v-if="!order.commentStatus">
                             <tui-button type="black" plain width="152rpx" height="56rpx" :size="26" shape="circle"
                                 @click.stop="addEvaluate(order.id)">评价晒单</tui-button>
                         </view>
                         <!-- 申请售后/退货按钮 -->
                         <view class="tui-btn-ml" v-if="canApplyAfterSale(order)">
                             <tui-button type="warning" plain width="152rpx" height="56rpx" :size="26" shape="circle"
                                 @click.stop="applyAfterSale(order)">申请售后</tui-button>
                         </view>
                         <view class="tui-btn-ml" v-else-if="hasAfterSaleInProgress(order)">
                             <tui-button type="info" plain width="152rpx" height="56rpx" :size="26" shape="circle"
                                 @click.stop="viewAfterSaleStatus(order)">售后进度</tui-button>
                         </view>
                     </template>
                     <template v-else-if="order.status === 40">
                         <!-- 已取消操作 -->
                         <view class="tui-btn-ml">
                             <tui-button type="black" plain width="152rpx" height="56rpx" :size="26" shape="circle"
                                 @click.stop="deleteOrder(order.id)">删除订单</tui-button>
                         </view>
                     </template>
                     <!-- 查看订单按钮 -->
                     <view class="tui-btn-ml">
                         <tui-button type="info" plain width="152rpx" height="56rpx" :size="26" shape="circle"
                             @click.stop="viewOrder(order.id)">查看订单</tui-button>
                     </view>
                 </view>

            </view>
                <tui-loadmore v-if="loading" :index="3" type="red"></tui-loadmore>
                <tui-nomore v-if="!hasMore" backgroundColor="#fafafa"></tui-nomore>
            </scroll-view>
        </view>
        
        <!-- 支付弹窗组件放在scroll-view外面，确保固定定位生效 -->
        <t-pay-way :show="show" :sub-order="subOrderInfo" :order-info="priceInfo" @close="popupClose"
            :balance="userBalance" @confirm="handleConfirmPayment"></t-pay-way>
            
        <!-- 申请退款弹窗 -->
        <tui-bottom-popup :show="showRefundModal" @close="closeRefundModal">
            <view class="refund-modal">
                <view class="refund-header">
                    <text class="refund-title">申请退款</text>
                    <text class="refund-close" @click="closeRefundModal">×</text>
                </view>
                <view class="refund-content">
                    <!-- 商品信息 -->
                    <view class="refund-goods">
                        <view class="refund-goods-title">退款商品</view>
                        <view class="refund-goods-item" v-for="(item, index) in currentRefundOrder.items" :key="index">
                            <image :src="item.picUrl" class="refund-goods-img"></image>
                            <view class="refund-goods-info">
                                <view class="refund-goods-name">{{ item.spuName }}</view>
                                <view class="refund-goods-attr">
                                    <span v-for="property in item.properties" :key="property.propertyId">
                                        {{ property.propertyName }}: {{ property.valueName }}
                                    </span>
                                </view>
                                <view class="refund-goods-price">￥{{ (item.payPrice / 100).toFixed(2) }} x{{ item.count }}</view>
                            </view>
                        </view>
                    </view>
                    
                    <!-- 退款类型 -->
                    <view class="refund-type">
                        <view class="refund-type-title">退款类型</view>
                        <radio-group @change="onRefundTypeChange">
                            <label class="refund-type-item" v-for="(type, index) in refundTypes" :key="index">
                                <radio :value="type.value" :checked="refundForm.type === type.value" color="#E41F19" />
                                <text class="refund-type-text">{{ type.label }}</text>
                            </label>
                        </radio-group>
                    </view>
                    
                    <!-- 退款原因 -->
                    <view class="refund-reason">
                        <view class="refund-reason-title">退款原因</view>
                        <picker @change="onReasonChange" :value="reasonIndex" :range="currentReasonList">
                            <view class="refund-reason-picker">
                                <text>{{ refundForm.reason || '请选择退款原因' }}</text>
                                <text class="refund-arrow">></text>
                            </view>
                        </picker>
                    </view>
                    
                    <!-- 退款金额 -->
                    <view class="refund-amount">
                        <view class="refund-amount-title">退款金额</view>
                        <view class="refund-amount-value">￥{{ (currentRefundOrder.payPrice / 100).toFixed(2) }}</view>
                    </view>
                    
                    <!-- 退款说明 -->
                    <view class="refund-description">
                        <view class="refund-description-title">退款说明</view>
                        <textarea 
                            v-model="refundForm.description" 
                            placeholder="请详细说明退款原因（选填）"
                            class="refund-description-textarea"
                            maxlength="200"
                        ></textarea>
                    </view>
                </view>
                <view class="refund-footer">
                    <tui-button type="black" plain width="200rpx" height="80rpx" :size="28" shape="circle" @click="closeRefundModal">取消</tui-button>
                    <tui-button type="danger" width="200rpx" height="80rpx" :size="28" shape="circle" @click="submitRefund">提交申请</tui-button>
                </view>
            </view>
        </tui-bottom-popup>
    </view>
</template>

<script>
    import tPayWay from "../components/views/t-pay-way/t-pay-way"
    export default {
        components: {
            tPayWay,
        },
        data() {
            return {
                tabs: [
                    { name: "全部" },
                    { name: "待支付" },
                    { name: "待发货" },
                    { name: "已发货" },
                    { name: "已完成" },
                    { name: "已取消" }
                ],
                currentTab: 0,
                orders: [], // 订单数据
                pageIndex: 1, // 当前页码
                pageSize: 10, // 每页数量
                hasMore: true, // 是否还有更多数据
                loading: false, // 是否在加载中
                scrollTop: 0,
                show: false, // 控制 tPayWay 组件的显示
                subOrderInfo: null, // 当前子订单信息
                priceInfo: {}, // 当前订单支付信息
                userBalance: 0, // 用户余额 (如果支付需要)
                checkTimer: null, // 订单过期检查定时器
                refresherTriggered: false, // 下拉刷新状态
                // 退款相关
                showRefundModal: false, // 显示退款弹窗
                currentRefundOrder: {}, // 当前申请退款的订单
                refundForm: {
                    type: '10', // 退款类型：10-仅退款，20-退款退货
                    reason: '', // 退款原因
                    description: '' // 退款说明
                },
                refundTypes: [
                    { label: '仅退款', value: '10' },
                    { label: '退款退货', value: '20' }
                ],
                refundReasons: [], // 从后台配置加载
                returnReasons: [], // 从后台配置加载
                currentReasonList: [], // 当前显示的原因列表
                reasonIndex: 0,
                refundApplications: {} // 退款申请缓存，key为订单ID，value为退款状态
            };
        },
        methods: {
            change(e) {
                this.currentTab = e.index;
                this.resetData();
                this.fetchOrders();
            },
            resetData() {
                this.orders = [];
                this.pageIndex = 1;
                this.hasMore = true;
            },
            // 下拉刷新
            onRefresh() {
                if (this.refresherTriggered) return;
                this.refresherTriggered = true;
                this.resetData();
                this.fetchOrders(true);
            },
            // 上拉加载
            onLoadMore() {
                if (!this.hasMore || this.loading) return;
                this.pageIndex++;
                this.fetchOrders();
            },
            // 查看订单详情
            viewOrder(orderId) {
                uni.navigateTo({
                    url: `../orderDetail/orderDetail?id=${orderId}`
                });
            },
            // 检查订单是否可以申请售后（参考 yudao-mall-uniapp 逻辑）
            canApplyAfterSale(order) {
                // 只有待发货、已发货、已完成状态的订单可以申请售后
                if (![10, 20, 30].includes(order.status)) {
                    return false;
                }
                
                // 检查订单项是否有可以申请售后的商品（afterSaleStatus === 0 表示可以申请）
                if (order.items && order.items.length > 0) {
                    return order.items.some(item => 
                        item.afterSaleStatus === 0 || item.afterSaleStatus === undefined
                    );
                }
                
                return false;
            },
            // 检查订单是否有售后在进行中
            hasAfterSaleInProgress(order) {
                if (order.items && order.items.length > 0) {
                    return order.items.some(item => 
                        item.afterSaleStatus && item.afterSaleStatus !== 0 && item.afterSaleStatus !== 20
                    );
                }
                return false;
            },
            // 申请售后（支持仅退款和退款退货）
            applyAfterSale(order) {
                // 找到第一个可以申请售后的订单项
                const availableItem = order.items.find(item => 
                    item.afterSaleStatus === 0 || item.afterSaleStatus === undefined
                );
                
                if (!availableItem) {
                    uni.showToast({
                        title: '该订单暂无可申请售后的商品',
                        icon: 'none'
                    });
                    return;
                }
                
                // 跳转到售后申请页面
                uni.navigateTo({
                    url: `../refund/refund?orderId=${order.id}&orderItemId=${availableItem.id}`
                });
            },
            // 查看售后状态
            viewAfterSaleStatus(order) {
                // 找到有售后状态的订单项
                const afterSaleItem = order.items.find(item => 
                    item.afterSaleStatus && item.afterSaleStatus !== 0
                );
                
                if (afterSaleItem && afterSaleItem.afterSaleId) {
                    // 跳转到售后详情页面
                    uni.navigateTo({
                        url: `../refundDetail/refundDetail?id=${afterSaleItem.afterSaleId}`
                    });
                } else {
                    // 如果没有售后ID，跳转到售后列表
                    uni.navigateTo({
                        url: '../refundList/refundList'
                    });
                }
            },
            // 删除订单
            deleteOrder(id) {
                uni.showModal({
                    title: "确认删除",
                    content: "您确定要删除订单吗？",
                    success: (res) => {
                        if (res.confirm) {
                            this.$api
                                .req(`/trade/order/delete`,{ id },"DELETE")
                                .then((res) => {
                                    if (res.code === 0) {
                                        uni.showToast({
                                            title: "订单已删除",
                                            icon: "none"
                                        });
                                        // 重新加载订单列表
                                        this.resetData();
                                        this.fetchOrders();
                                    } else {
                                        uni.showToast({
                                            title: res.msg || "删除失败",
                                            icon: "none"
                                        });
                                    }
                                })
                                .catch(() => {
                                    uni.showToast({
                                        title: "删除失败，请重试",
                                        icon: "none"
                                    });
                                });
                        }
                    }
                });
            },
            fetchOrders(isRefresh = false) {
                if (this.loading || !this.hasMore) return;
                this.loading = true;

                const statusMap = [null,0,10,20,30,40]; // 全部, 待支付, 待发货, 已发货, 已完成, 已取消
                const status = statusMap[this.currentTab];

                let params = {
                    pageNo: this.pageIndex,
                    pageSize: this.pageSize,
                };

                if (status !== null) {
                    params.status = status;
                    if (status === 30) {
                        params.commentStatus = false; // 仅待评价时添加
                    }
                }

                this.$api
                    .req(`/trade/order/page`,params,"GET")
                    .then((res) => {
                        if (res.code === 0) {
                            const data = res.data.list;
                            this.orders = [...this.orders,...data];
                            this.hasMore = data.length >= this.pageSize; // 如果返回的数据少于pageSize，说明没有更多数据了
                        } else {
                            uni.showToast({
                                title: res.msg || "加载失败",
                                icon: "none"
                            });
                        }
                    })
                    .finally(() => {
                        this.loading = false;
                        if (isRefresh) {
                            this.refresherTriggered = false;
                        }
                    });
            },
            // 检查订单是否过期
            checkOrderExpired() {
                // 只在待支付tab时才检查
                if (this.currentTab !== 1) return;
                
                const now = new Date().getTime();
                const expiredOrders = [];
                
                this.orders.forEach((order, index) => {
                    // 只检查待支付状态的订单
                    if (order.status === 0 && order.createTime) {
                        // 后端返回的是毫秒级时间戳，直接使用
                        const orderCreateTime = order.createTime;
                        const elapsed = Math.floor((now - orderCreateTime) / 1000); // 已过秒数
                        const validTime = 15 * 60; // 15分钟有效期
                        
                        if (elapsed >= validTime) {
                            expiredOrders.push({ order, index });
                        }
                    }
                });
                
                // 如果有过期订单，更新状态
                if (expiredOrders.length > 0) {
                    this.updateExpiredOrders(expiredOrders);
                }
            },
            // 更新过期订单状态（仅前端展示，不请求后端）
            updateExpiredOrders(expiredOrders) {
                expiredOrders.forEach(({ order, index }) => {
                    // 不修改后端状态，只刷新展示与按钮逻辑
                    this.orders[index].status = 0; // 保持原始状态为待支付
                });
                
                // 只更新视图，不重新加载数据
                this.$forceUpdate();
            },
            // 判断订单是否已过期（超过15分钟）
            isOrderExpired(order) {
                if (!order.createTime) return false;
                
                const now = new Date().getTime();
                const orderCreateTime = order.createTime;
                const elapsed = Math.floor((now - orderCreateTime) / 1000);
                const validTime = 15 * 60; // 15分钟有效期
                
                return elapsed >= validTime;
            },
            // 计算订单剩余时间
            getOrderRemainingTime(order) {
                if (!order.createTime) return 0;
                
                const now = new Date().getTime();
                const orderCreateTime = order.createTime;
                const elapsed = Math.floor((now - orderCreateTime) / 1000);
                const validTime = 15 * 60; // 15分钟有效期
                const remaining = validTime - elapsed;
                
                return Math.max(0, remaining);
            },
            // 格式化订单时间显示（倒计时）
            formatOrderTime(seconds) {
                const minutes = Math.floor(seconds / 60);
                const remainingSeconds = seconds % 60;
                return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
            },
            // 格式化订单创建时间（年月日时分秒）
            formatOrderCreateTime(timestamp) {
                if (!timestamp) return '';
                
                const date = new Date(timestamp);
                const year = date.getFullYear();
                const month = (date.getMonth() + 1).toString().padStart(2, '0');
                const day = date.getDate().toString().padStart(2, '0');
                const hours = date.getHours().toString().padStart(2, '0');
                const minutes = date.getMinutes().toString().padStart(2, '0');
                const seconds = date.getSeconds().toString().padStart(2, '0');
                
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            },
            // 启动订单过期检查定时器
            startOrderExpiredCheck() {
                // 每1秒更新一次倒计时显示
                this.checkTimer = setInterval(() => {
                    // 强制更新视图以刷新倒计时显示
                    this.$forceUpdate();
                    
                    // 只在待支付tab且有订单时才检查过期
                    if (this.currentTab === 1 && this.orders.length > 0) {
                        this.checkOrderExpired();
                    }
                }, 1000);
            },
            // 停止订单过期检查定时器
            stopOrderExpiredCheck() {
                if (this.checkTimer) {
                    clearInterval(this.checkTimer);
                    this.checkTimer = null;
                }
            },
            // 确认取消订单
            cancelOrder(id) {
                uni.showModal({
                    title: "确认取消",
                    content: "您确定要取消订单吗？",
                    success: (res) => {
                        if (res.confirm) {
                            // 用户点击确认后调用取消接口
                            this.performCancelOrder(id);
                        } else if (res.cancel) {
                            uni.showToast({
                                title: "已取消操作",
                                icon: "none"
                            });
                        }
                    }
                });
            },
            // 调用取消订单接口
            performCancelOrder(id) {
                this.$api
                    .req(`/trade/order/cancel`,{ id },"DELETE")
                    .then((res) => {
                        if (res.code === 0) {
                            uni.showToast({
                                title: "订单已取消",
                                icon: "none"
                            });
                            this.resetData();
                            this.fetchOrders();
                        } else {
                            uni.showToast({
                                title: res.msg || "取消失败",
                                icon: "none"
                            });
                        }
                    })
                    .catch(() => {
                        uni.showToast({
                            title: "取消失败，请重试",
                            icon: "none"
                        });
                    });
            },
            // 打开支付组件
            continuePayment(order) {
                this.subOrderInfo = order;
                this.priceInfo = {
                    payPrice: order.payPrice, // 支付金额
                    orderId: order.id,
                };
                this.show = true; // 显示支付组件
            },
            // 关闭支付弹窗
            popupClose() {
                this.show = false;
            },
            // 支付确认事件
            handleConfirmPayment({ payMethod }) {
                uni.showToast({
                    title: `选择了支付方式：${payMethod}`,
                    icon: "none"
                });
                this.show = false; // 关闭支付弹窗
            },
            // 确认收货
            confirmOrder(id) {
                uni.showModal({
                    title: "确认收货",
                    content: "请确认您已收到商品",
                    success: (res) => {
                        if (res.confirm) {
                            this.$api
                                .req(`/trade/order/confirm`,{ id },"DELETE")
                                .then((res) => {
                                    if (res.code === 0) {
                                        uni.showToast({
                                            title: "确认收货成功",
                                            icon: "success"
                                        });
                                        this.resetData();
                                        this.fetchOrders();
                                    } else {
                                        uni.showToast({
                                            title: res.msg || "确认失败",
                                            icon: "none"
                                        });
                                    }
                                })
                                .catch(() => {
                                    uni.showToast({
                                        title: "确认失败，请重试",
                                        icon: "none"
                                    });
                                });
                        }
                    }
                });
            },
            // 评价订单
            addEvaluate(id) {
                uni.navigateTo({
                    url: `../addEvaluate/addEvaluate?orderId=${id}`
                });
            },
            getStatusText(status) {
                const statusMap = {
                    0: "待支付",
                    10: "待发货",
                    20: "已发货",
                    30: "已完成",
                    40: "已取消",
                    50: "已退款",
                    60: "退款中"
                };
                return statusMap[status] || "未知状态";
            },
            // 获取退款状态文本
            getRefundStatusText(order) {
                // 根据订单的退款状态返回相应的文本
                if (order.refundStatus) {
                    const refundStatusMap = {
                        10: "退款申请中",
                        20: "退款处理中", 
                        30: "退款已完成",
                        40: "退款已拒绝"
                    };
                    return refundStatusMap[order.refundStatus] || "退款处理中";
                }
                
                // 根据订单项状态判断
                if (order.items && order.items.length > 0) {
                    const item = order.items[0];
                    if (item.afterSaleStatus) {
                        const afterSaleStatusMap = {
                            10: "退款申请中",
                            20: "退款处理中",
                            30: "退款已完成", 
                            40: "退款已拒绝"
                        };
                        return afterSaleStatusMap[item.afterSaleStatus] || "退款处理中";
                    }
                }
                
                return "退款处理中";
            },
            onReachBottom() {
                if (!this.hasMore || this.loading) return;
                this.pageIndex++;
                this.fetchOrders();
            },
            onPageScroll(e) {
                this.scrollTop = e.scrollTop;
            },
            // 申请退款
            applyRefund(order) {
                this.currentRefundOrder = order;
                this.showRefundModal = true;
                // 重置表单
                this.refundForm = {
                    type: '10',
                    reason: '',
                    description: ''
                };
                this.reasonIndex = 0;
                // 加载交易配置
                this.loadTradeConfig();
            },
            // 关闭退款弹窗
            closeRefundModal() {
                this.showRefundModal = false;
            },
            // 加载交易配置
            loadTradeConfig() {
                this.$api
                    .req('/trade/config/get', {}, 'GET')
                    .then((res) => {
                        if (res.code === 0 && res.data) {
                            // 加载退款原因
                            this.refundReasons = res.data.afterSaleRefundReasons || [];
                            // 加载退货原因
                            this.returnReasons = res.data.afterSaleReturnReasons || [];
                            
                            // 根据当前选择的类型设置原因列表
                            this.updateReasonList();
                        } else {
                            // 如果加载失败，使用默认原因
                            this.setDefaultReasons();
                        }
                    })
                    .catch(() => {
                        // 如果加载失败，使用默认原因
                        this.setDefaultReasons();
                    });
            },
            // 设置默认原因
            setDefaultReasons() {
                this.refundReasons = [
                    '商品质量问题',
                    '商品与描述不符',
                    '收到商品破损',
                    '发错商品',
                    '不想要了',
                    '其他原因'
                ];
                this.returnReasons = [
                    '商品质量问题',
                    '商品与描述不符',
                    '收到商品破损',
                    '发错商品',
                    '不想要了',
                    '其他原因'
                ];
                this.updateReasonList();
            },
            // 更新原因列表
            updateReasonList() {
                if (this.refundForm.type === '10') {
                    // 仅退款
                    this.currentReasonList = this.refundReasons;
                } else {
                    // 退款退货
                    this.currentReasonList = this.returnReasons;
                }
            },
            // 退款类型改变
            onRefundTypeChange(e) {
                this.refundForm.type = e.detail.value;
                this.updateReasonList();
                // 清空已选择的原因
                this.refundForm.reason = '';
                this.reasonIndex = 0;
            },
            // 退款原因改变
            onReasonChange(e) {
                this.reasonIndex = e.detail.value;
                this.refundForm.reason = this.currentReasonList[e.detail.value];
            },
            // 提交退款申请
            submitRefund() {
                if (!this.refundForm.reason) {
                    uni.showToast({
                        title: '请选择退款原因',
                        icon: 'none'
                    });
                    return;
                }
                
                uni.showModal({
                    title: '确认申请',
                    content: '确定要申请退款吗？',
                    success: (res) => {
                        if (res.confirm) {
                            this.performRefund();
                        }
                    }
                });
            },
            // 执行退款申请
            performRefund() {
                const refundData = {
                    orderId: this.currentRefundOrder.id,
                    orderItemId: this.currentRefundOrder.items[0].id, // 取第一个商品项
                    refundPrice: this.currentRefundOrder.payPrice,
                    way: parseInt(this.refundForm.type),
                    applyReason: this.refundForm.reason,
                    applyDescription: this.refundForm.description,
                    images: [] // 暂时不传图片
                };
                
                this.$api
                    .createRefund(refundData)
                    .then((res) => {
                        if (res.code === 0) {
                            uni.showToast({
                                title: '退款申请已提交',
                                icon: 'success'
                            });
                            // 更新退款申请缓存
                            this.refundApplications[this.currentRefundOrder.id] = {
                                status: 10, // 申请中
                                applyTime: new Date().getTime()
                            };
                            this.closeRefundModal();
                            // 刷新订单列表
                            this.resetData();
                            this.fetchOrders();
                        } else {
                            uni.showToast({
                                title: res.msg || '申请失败',
                                icon: 'none'
                            });
                        }
                    })
                    .catch(() => {
                        uni.showToast({
                            title: '申请失败，请重试',
                            icon: 'none'
                        });
                    });
            },
            // 复制订单号
            copyOrderNo(orderNo) {
                if (!orderNo) return;
                
                uni.setClipboardData({
                    data: orderNo,
                    success: () => {
                        uni.showToast({
                            title: '订单号已复制',
                            icon: 'success'
                        });
                    },
                    fail: () => {
                        uni.showToast({
                            title: '复制失败',
                            icon: 'none'
                        });
                    }
                });
            }
        },
        onLoad() {
            this.fetchOrders();
            this.startOrderExpiredCheck();
            // 加载交易配置
            this.loadTradeConfig();
        },
        onUnload() {
            this.stopOrderExpiredCheck();
        },
        onHide() {
            this.stopOrderExpiredCheck();
        },
        onShow() {
            this.startOrderExpiredCheck();
        }
    };
</script>




<style>
    .container {
        padding-bottom: env(safe-area-inset-bottom);
    }

    .tui-order-list {
        margin-top: 80rpx;
    }

    .tui-order-item {
        margin-top: 20rpx;
        border-radius: 10rpx;
        overflow: hidden;
    }

    .tui-goods-title {
        width: 100%;
        font-size: 28rpx;
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
    }
    
    .tui-order-info {
        display: flex;
        flex-direction: column;
        gap: 4rpx;
    }
    
    .tui-order-number {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 12rpx;
    }
    
    .tui-copy-btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        margin-left: 12rpx;
        background: #ffffff;
        border-radius: 20rpx;
        border: 1rpx solid #E41F19;
        width: 75rpx;
        height: 40rpx;
        font-size: 22rpx;
        font-weight: 400;
        color: #E41F19;
        padding: 0;
        box-sizing: border-box;
    }
    
    .tui-copy-btn:active {
        opacity: 0.7;
        background: #f5f5f5;
    }
    
    .tui-order-time {
        font-size: 24rpx;
        color: #999;
    }

    .tui-order-status {
        color: #888;
        font-size: 26rpx;
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        justify-content: center;
    }
    
    .tui-order-status-content {
        display: flex;
        flex-direction: row;
        align-items: center;
        gap: 8rpx;
    }
    
    .tui-order-countdown {
        font-size: 22rpx;
        color: #ff4444;
        padding: 2rpx 8rpx;
        background: #fff5f5;
        border-radius: 8rpx;
        border: 1rpx solid #ffcdd2;
        font-weight: 500;
    }
    
    .tui-order-expired {
        font-size: 22rpx;
        color: #999;
        margin-top: 4rpx;
        padding: 2rpx 8rpx;
        background: #f5f5f5;
        border-radius: 8rpx;
        border: 1rpx solid #ddd;
        font-weight: 500;
    }
    
    .tui-refund-status {
        font-size: 20rpx;
        color: #ff6b35;
        margin-top: 4rpx;
        padding: 2rpx 8rpx;
        background: #fff5f0;
        border-radius: 8rpx;
        border: 1rpx solid #ffb3a0;
        font-weight: 500;
    }

    .tui-goods-item {
        width: 100%;
        padding: 20rpx 30rpx;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
    }

    .tui-goods-img {
        width: 180rpx;
        height: 180rpx;
        display: block;
        flex-shrink: 0;
    }

    .tui-goods-center {
        flex: 1;
        padding: 20rpx 8rpx;
        box-sizing: border-box;
    }

    .tui-goods-name {
        max-width: 310rpx;
        word-break: break-all;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
         -webkit-line-clamp: 2;
         line-clamp: 2;
        font-size: 26rpx;
        line-height: 32rpx;
    }

    .tui-goods-attr {
        font-size: 22rpx;
        color: #888888;
        line-height: 32rpx;
        padding-top: 20rpx;
        word-break: break-all;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
         -webkit-line-clamp: 2;
         line-clamp: 2;
    }

    .tui-price-right {
        text-align: right;
        font-size: 24rpx;
        color: #888888;
        line-height: 30rpx;
        padding-top: 20rpx;
    }

    .tui-color-red {
        color: #E41F19;
        padding-right: 30rpx;
    }

    .tui-goods-price {
        width: 100%;
        display: flex;
        align-items: flex-end;
        justify-content: flex-end;
        font-size: 24rpx;
    }

    .tui-size-24 {
        font-size: 24rpx;
        line-height: 24rpx;
    }

    .tui-price-large {
        font-size: 32rpx;
        line-height: 30rpx;
        font-weight: 500;
    }

    .tui-order-btn {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        background: #fff;
        padding: 10rpx 30rpx 20rpx;
        box-sizing: border-box;
    }

    .tui-btn-ml {
        margin-left: 20rpx;
    }
    
    /* 退款弹窗样式 */
    .refund-modal {
        background: #fff;
        border-radius: 20rpx 20rpx 0 0;
        max-height: 80vh;
        overflow-y: auto;
    }
    
    .refund-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 30rpx;
        border-bottom: 1rpx solid #f0f0f0;
    }
    
    .refund-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
    }
    
    .refund-close {
        font-size: 40rpx;
        color: #999;
        line-height: 1;
    }
    
    .refund-content {
        padding: 30rpx;
    }
    
    .refund-goods {
        margin-bottom: 30rpx;
    }
    
    .refund-goods-title {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 20rpx;
    }
    
    .refund-goods-item {
        display: flex;
        padding: 20rpx;
        background: #f8f8f8;
        border-radius: 10rpx;
        margin-bottom: 10rpx;
    }
    
    .refund-goods-img {
        width: 120rpx;
        height: 120rpx;
        border-radius: 8rpx;
        margin-right: 20rpx;
    }
    
    .refund-goods-info {
        flex: 1;
    }
    
    .refund-goods-name {
        font-size: 26rpx;
        color: #333;
        margin-bottom: 10rpx;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
    }
    
    .refund-goods-attr {
        font-size: 22rpx;
        color: #666;
        margin-bottom: 10rpx;
    }
    
    .refund-goods-price {
        font-size: 24rpx;
        color: #E41F19;
        font-weight: bold;
    }
    
    .refund-type, .refund-reason, .refund-amount, .refund-description {
        margin-bottom: 30rpx;
    }
    
    .refund-type-title, .refund-reason-title, .refund-amount-title, .refund-description-title {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 20rpx;
    }
    
    .refund-type-item {
        display: flex;
        align-items: center;
        padding: 15rpx 0;
    }
    
    .refund-type-text {
        margin-left: 20rpx;
        font-size: 26rpx;
        color: #333;
    }
    
    .refund-reason-picker {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx;
        background: #f8f8f8;
        border-radius: 10rpx;
        font-size: 26rpx;
        color: #333;
    }
    
    .refund-arrow {
        color: #999;
        font-size: 24rpx;
    }
    
    .refund-amount {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx;
        background: #f8f8f8;
        border-radius: 10rpx;
    }
    
    .refund-amount-value {
        font-size: 28rpx;
        color: #E41F19;
        font-weight: bold;
    }
    
    .refund-description-textarea {
        width: 100%;
        min-height: 120rpx;
        padding: 20rpx;
        background: #f8f8f8;
        border-radius: 10rpx;
        font-size: 26rpx;
        color: #333;
        border: none;
        outline: none;
    }
    
    .refund-footer {
        display: flex;
        justify-content: space-around;
        padding: 30rpx;
        border-top: 1rpx solid #f0f0f0;
        background: #fff;
    }
</style>